<!--bom备料清单-->
<script setup>
import { getMallFileDownLoadPath } from '@/server/api/file';
import NumberPatches from '@/components/upLoad/NumberPatches.vue';
import UpLoad from '@/components/upLoad/UpLoad.vue';
import AnalyseFile from '@/components/upLoad/AnalyseFile.vue';
import { ref, reactive, onMounted, computed } from 'vue';
import { deleteFile, getqueryBomPageList, inquireFile } from '@/server/api/biz.js';
import { uploadDocFile } from '@/server/api/file';
import { useRouter } from 'vue-router';
import { downloadFile } from '@/utils/common.js';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
let visible = ref(false);
const flieData = ref(null);
const fileUploadRequest = ref(null);
const activeId = ref(1);
const background = ref(true);
const loading = ref(true);
const query = reactive({
  keywords: '',
  startDate: '',
  endDate: '',
});
const ids = ref([]);
const bomData = ref([]);
const statusList = computed(() => ({
  1: t('smt.awaitingprocessing'),
  2: t('smt.Inprogress'),
  3: t('smt.processingfailure'),
  4: t('smt.Processingsuccess'),
}));
const router = useRouter();
let total = ref(0);
let pages = ref(1);
let size = ref(10);
let current = ref('');

/**
 * 获取文件列表
 * @param {*} param
 */
const getFlieList = (param) => {
  loading.value = true;
  getqueryBomPageList(param).then((res) => {
    console.log(res, '获取');
    if (res.code == 200) {
      dataProcessing(res.data);
      loading.value = false;
    }
  });
};

const dataProcessing = (data) => {
  const arr = [];
  data.records.forEach((item) => {
    arr.push({
      id: item.id,
      fileName: item.fileName,
      quantity: item.quantity,
      privateInventory: item.bomMatchList != null ? item.bomMatchList[2] : 0,
      order: item.bomMatchList != null ? item.bomMatchList[1] : 0,
      mailed: item.bomMatchList != null ? item.bomMatchList[3] : 0,
      status: statusList[item.parseStatus],
      createTime: item.createTime,
      fileSerial: item.fileSerial,
      quantity: item.quantity,
    });
  });
  total.value = Number(data.total);
  // pages.value = Number(data.pages);
  size.value = Number(data.size);
  current.value = Number(data.current);
  bomData.value = arr;
};

onMounted(() => {
  const obj = {
    current: 1,
    fileName: query.keywords,
    pageSize: 10,
    parseStatus: '',
  };
  getFlieList(obj);
});

/**
 * 下载BOM文件模板
 */
const downloadBom = () => {
  getMallFileDownLoadPath('BOM模板.xlsx').then((res) => {
    if (res.code == 200) {
      downloadFile(res.data.mallFileDownloadPath.bomFilePath);
    }
  });
};

/**
 * 获取弹框布尔值
 * @param {*} isbo
 */
const getModea = (isbo) => {
  visible.value = isbo;
};

/**
 * 获取上传文件的flie值
 * @param {*} flie
 */
const getFlieData = (flie) => {
  console.log(flie.raw, '获取');
  flieData.value = flie;
};

/**
 * 获取文件更新数据
 * @param {*} data
 */
const onConfirm = (num) => {
  const obj = {
    fileType: 2,
    batchYearLimit: 0, // 接受批次(默认0 不限)
    isUseAlternative: 1, // 是否接受替(1接受，2不接受 默认1）
    smtLayer: 1, // 贴片层(1全贴，2顶层，3底层,默认1全贴)
    quantity: num,
    file: flieData.value,
  };
  uploadDocFile(obj).then((res) => {
    if (res.code === 200) {
      ElMessage.success(t('mall.upload_successful'));
      fileUploadRequest.value = res.data;
      visible.value = false;
    } else {
      ElMessage.error(res.msg);
    }
    // emit('getModea', false);
  });
};

/**
 * 重新上传
 */
const reUpload = () => {
  fileUploadRequest.value = null;
  flieData.value = null;
};

const switchEvent = (item) => {
  activeId.value = item.id;
};

/**
 * 选中列表数据
 * @param {} val
 */
const handleSelectionChange = (val) => {
  const arr = [];
  val.forEach((item) => {
    console.log(item);
    arr.push(item.id);
  });
  ids.value = arr;
};

const exportBom = () => {};

/**
 * 删除选项
 */
const deleteBom = () => {
  const obj = {
    ids: ids.value.join(','),
  };
  deleteFile(obj).then((res) => {
    console.log(res);
    if (res.code == 200) {
      ElMessage.success(t('mall.delete_successful'));
      inquireList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 查询
 */
const inquireList = () => {
  const obj = {
    current: 1,
    fileName: query.keywords,
    pageSize: 10,
    parseStatus: '',
  };
  getFlieList(obj);
};

/**
 * 改变页数
 * @param {*} val
 */
const handleSizeChange = (val) => {
  pages.value = val;
  const obj = {
    current: val,
    fileName: query.keywords,
    pageSize: 10,
    parseStatus: '',
  };
  getFlieList(obj);
};

/**
 * 分页
 * @param {*} val
 */
const handleCurrentChange = (val) => {
  pages.value = val;
  const obj = {
    current: val,
    fileName: query.keywords,
    pageSize: 10,
    parseStatus: '',
  };
  getFlieList(obj);
};

const modifyMaterialAllocation = (index, row) => {
  const { fileName, fileSerial, quantity, id } = row;
  router.push({
    path: '/quotation',
    query: {
      bomName: fileName,
      fileSerial,
      num: quantity,
      bomFileId: id,
    },
  });
};

const smtOrder = (index, row) => {
  console.log(index, row);
  sessionStorage.removeItem('cacheData');
  router.push({
    path: '/pricing/smt',
    query: {
      bomFileId: row.id,
      name: row.fileName,
      quantity: row.quantity,
    },
  });
};
</script>
<template>
  <div>
    <div class="bom-upload">
      <UpLoad
        @getModea="getModea"
        @getFlieData="getFlieData"
        :name="$t('smt.UploadBOMfiles')"
        :warningTitle="$t('mall.smt_quantity')"
        :fileType="'2'"
        v-if="fileUploadRequest == null"
      >
        <div>
          <p class="upload-tip desc">{{ $t('om.Wewillcalculate') }}</p>
          <p class="upload-tip">{{ $t('om.SupportExcelfile') }}</p>
          <div class="downloadBom" @click="downloadBom">{{ $t('om.DownloadBOMfile') }}</div>
        </div>
      </UpLoad>
      <AnalyseFile
        v-if="fileUploadRequest != null"
        :fileUploadRequest="fileUploadRequest"
        @reUpload="reUpload"
        @inquireList="inquireList"
      />
    </div>

    <div class="mian">
      <div class="timer">
        <el-input :placeholder="$t('om.Pleaseentercomponentkeywords')" v-model="query.keywords" />
        <!-- <span class="text">订单时间</span>
        <el-date-picker v-model="query.startDate" type="date" placeholder="开始日期" :size="size" />
        <span class="solid"></span>
        <el-date-picker v-model="query.endDate" type="date" placeholder="结束日期" :size="size" /> -->
        <div>
          <el-button class="inquires" @click="inquireList">{{ $t('om.Search') }}</el-button>
        </div>
      </div>
      <div class="operate">
        <el-button @click="exportBom">{{ $t('om.ExportBOM') }}</el-button>
        <el-button @click="deleteBom">{{ $t('om.Deleting') }}</el-button>
      </div>
      <div class="table">
        <el-table
          v-loading="loading"
          :data="bomData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="fileName" :label="$t('smt.BOMInfo')" width="">
            <template #default="scope">
              <div class="f-12">《{{ scope.row.fileName }}》</div>
              <div class="f-12">{{ scope.row.createTime }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" :label="$t('smt.Numberofpatches')" />
          <el-table-column prop="address" :label="$t('smt.PreparedComponents')">
            <el-table-column prop="privateInventory" :label="$t('smt.Privatestock')">
            </el-table-column>
            <!-- <el-table-column prop="address" label="IBE现货"> </el-table-column> -->
            <el-table-column prop="order" :label="$t('smt.IBEorderrequired')"> </el-table-column>
            <el-table-column prop="mailed" :label="$t('smt.Tobesent')"> </el-table-column>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('smt.Operational')" width="320">
            <template #default="scope">
              <el-button
                type="warning"
                size="small"
                @click.prevent="modifyMaterialAllocation(scope.$index, scope.row)"
              >
                {{ $t('mall.modify') }}
              </el-button>
              <el-button type="success" size="small">
                {{ $t('om.UnlockingPrivateInventory') }}
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click.prevent="smtOrder(scope.$index, scope.row)"
              >
                {{ $t('om.PlaceSMTorders') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="m-16">
          <el-pagination
            v-if="total > 0"
            :background="background"
            v-model:current-page="pages"
            v-model:page-size="size"
            layout="total,size, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
  <NumberPatches
    v-if="visible"
    v-model="visible"
    @getModea="getModea"
    :flieData="flieData"
    @confirm="onConfirm"
  />
</template>
<style scoped lang="scss">
.m-16 {
  margin-top: 16px;
}
.top {
  display: contents;
  justify-content: space-between;
  margin-bottom: 10px;
}
.f-12 {
  font-size: 12px;
  color: #383838;
}
.bottom {
  display: flex;
}
.upload-tip {
  text-align: center;
  color: #a6a6a6;
  font-size: 14px;
  &.desc {
    padding-top: 16px;
    color: var(--mall-text-color-primary);
  }
}
.downloadBom {
  text-align: center;
  color: #5255fe;
  font-size: 14px;
  cursor: pointer;
  margin-top: 20px;
}

.bom-upload {
  width: 100%;
  height: 350px;
  background-color: var(--mall-body-bg-color);
  border-radius: 8px;
  display: grid;
  justify-content: center;
  margin-top: 12px;
}
.mian {
  width: 100%;
  margin-top: 24px;

  .header {
    display: flex;
    span {
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: var(--mall-text-color-primary);
      cursor: pointer;
    }

    .active {
      color: var(--mall-color-primary);
      text-decoration: underline;
    }
  }
  .timer {
    display: flex;
    align-items: center;
    margin-top: 24px;
    span {
      margin-left: 24px;
      color: var(--mall-text-color-primary);
    }
    .text {
      margin-right: 16px;
    }
    .el-input__wrapper {
      margin-left: 20px;
    }
    .inquires {
      background-color: var(--mall-color-primary);
      color: var(--mall-header-bg);
    }
    .solid {
      width: 16px;
      height: 2px;
      border-radius: 2px;
      opacity: 1;
      background: #cccccc;
      margin-right: 18px;
    }
    .el-input {
      width: 180px;
    }
    .el-button {
      margin-left: 24px;
    }
  }

  .operate {
    margin-top: 16px;
    .el-button {
      width: 140px;
      border: 1px solid var(--mall-color-primary);
      color: var(--mall-color-primary);
    }
  }

  .table {
    margin-top: 16px;
  }
}
</style>
